import axios from "axios";
import qs from "qs";

const instance = axios.create({ timeout: 60000 });

instance.interceptors.request.use((req) => {
  if (req.method === "post") {
    req.headers = {
      ...req.headers,
      "Content-Type": "application/x-www-form-urlencoded",
    };
    req.data = qs.stringify(req.data);
    return req;
  }
});

instance.interceptors.response.use(
  (resp) => {
    if (resp.data.status > 299 || resp.data.status < 200) {
      return Promise.reject(resp.data?.msg);
    }
    return resp.data;
  },
  (err) => {
    if (err.response && err.response.status >= 400) {
      return Promise.reject(
        err.response?.data.msg.length > 15
          ? `响应状态码${err.response?.status},详情请查看network`
          : err.response.data.msg
      );
    }
    return Promise.reject("网络异常");
  }
);

export default instance;
